import java.sql.*;
import java.util.*;

public abstract class Client extends Thread {
	Connection connection;
	ArrayList<Result> result;
	int iterations;
	int clientID;
	
	public Client(int _iterations, int _clientID) {
		connection = DB.Connect();
		result = new ArrayList<Result>();
		iterations = _iterations;
		clientID = _clientID;
	}
	
	public ArrayList<Result> GetResult() {
		return result;
	}
	
	public double GetThroughput() {
		long totalTime = 0;
		long totalQueriesNumber = 0;
		for(Result r : result) {
			if(r.success == true) {
				totalTime += r.getMilliseconds();
				totalQueriesNumber ++;
			}
		}
		return ((double)(1000 * totalQueriesNumber)) / ((double)totalTime);
	}
	
	protected void RunUpdate(String updateName, String sql) {
		Statement stmt;
		try {
			stmt = connection.createStatement();
		} catch(SQLException e) {
			System.err.println("Could not create statement for " + updateName);
			e.printStackTrace();
			return;
		}
		System.err.println("Client " + clientID + " - " + updateName + " => starting...");
		
		try {
			stmt.execute(sql);
			
			System.err.println("Client " + clientID + " - " + updateName + " => finished");
		} catch(SQLException e) {
			System.err.println("<<<" + sql + ">>>" + "\n" + "--> Statement failed! Check output console");
			e.printStackTrace();
		}
	}
	
	protected void RunQuery(String queryName, String sql) {
		Statement stmt;
		try {
			stmt = connection.createStatement();
		} catch(SQLException e) {
			System.err.println("Could not create statement for " + queryName);
			e.printStackTrace();
			result.add(new Result(clientID, queryName, 0, false));
			return;
		}
		System.err.println("Client " + clientID + " - " + queryName + " => starting...");
		
		long start = System.currentTimeMillis();
		try {
			ResultSet rs = stmt.executeQuery(sql);
			long stop = System.currentTimeMillis();
			
			int rowCount = 0;
			while(rs.next()) {
				rowCount ++;
			}
			rs.close();
			
			System.err.println("Client " + clientID + " - " + queryName + " => " + rowCount + " rows");
			result.add(new Result(clientID, queryName, stop-start, true));
		} catch(SQLException e) {
			long stop = System.currentTimeMillis();
			result.add(new Result(clientID, queryName, stop-start, false));
			System.err.println("<<<" + sql + ">>>" + "\n" + "--> Statement failed! Check output console");
			e.printStackTrace();
		}
	}
}
